package org.example.new_hbps_backend_reconstruction.mapper;

/**
 * @author 丁利军
 * @date 2025年10月15日 19:20
 * @description 血氧数据表的mapper
 */
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.new_hbps_backend_reconstruction.entity.BloodOxygenLogsEntity;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface BloodOxygenLogsMapper extends BaseMapper<BloodOxygenLogsEntity> {
    // 1. 查找最新一条
    @Select("SELECT * FROM blood_oxygen_logs WHERE patient_uid = #{patientUid} ORDER BY upload_time DESC LIMIT 1")
    BloodOxygenLogsEntity findLatestByPatientUid(@Param("patientUid") Long patientUid);

    // 2. 分页查找
    IPage<BloodOxygenLogsEntity> selectPageByPatientUid(Page<?> page, @Param("patientUid") Long patientUid);

    // 3. 根据日期查找
    @Select("SELECT * FROM blood_oxygen_logs " +
            "WHERE patient_uid = #{patientUid} " +
            "AND DATE(upload_time) = #{date} " +
            "ORDER BY upload_time DESC")
    List<BloodOxygenLogsEntity> findByPatientUidAndDate(@Param("patientUid") Long patientUid,
                                                        @Param("date") LocalDate date);

    // 4. 查找所有
    @Select("SELECT * FROM blood_oxygen_logs WHERE patient_uid = #{patientUid} ORDER BY upload_time DESC")
    List<BloodOxygenLogsEntity> findAllByPatientUid(@Param("patientUid") Long patientUid);

    // 5. 统计数据量
    @Select("SELECT COUNT(*) FROM blood_oxygen_logs " +
            "WHERE patient_uid = #{patientUid} " +
            "AND DATE(upload_time) = #{date}")
    Long countByPatientUidAndDate(@Param("patientUid") Long patientUid,
                                  @Param("date") LocalDate date);

    // 6. 计算平均血氧值
    @Select("SELECT AVG(spo2) FROM blood_oxygen_logs " +
            "WHERE patient_uid = #{patientUid} " +
            "AND DATE(upload_time) = #{date}")
    Double averageSpo2ByPatientUidAndDate(@Param("patientUid") Long patientUid,
                                          @Param("date") LocalDate date);
}

